<html>
<head>
    <title>test</title>
</head>
<body>
    <input type="file" id="asd" accept="image/*">
<img src="" id="ima" style="display: none">
</body>
<script>
    let imageCache = new Image();
    let readFile=new FileReader();
    let f=document.getElementById("asd");
    let asdasd=document.getElementById("ima");
    f.addEventListener("change",function (){
        // console.log(f.files[0].size/1024/1024);
        readFile.readAsDataURL(f.files[0]);
        readFile.onload=function (evt) {
            console.log("压缩前大小："+evt.target.result.length/1024/1024)    //单位MB，base64编码大小
            asdasd.src=evt.target.result.toString();
            if (evt.target.result.length>1024*1024/2){ // 512kb便压缩
                console.log("压缩后大小："+getBase64Image(asdasd).length/1024/1024);
                console.log(getBase64Image(asdasd));
            }else {
                console.log("没被压缩，大小依旧为："+evt.target.result.length/1024/1024)
            }
        }
    });
    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        var width = img.width;
        var height = img.height;
        // calculate the width and height, constraining the proportions
        if (width > height) {
            if (width > 160) {
                height = Math.round(height *= 160 / width);
                width = 160;
            }
        } else {
            if (height > 90) {
                width = Math.round(width *= 90 / height);
                height = 90;
            }
        }
        canvas.width = width;  /*设置新的图片的宽度*/
        canvas.height = height; /*设置新的图片的长度*/
        var ctx = canvas.getContext("2d");//开启canvas绘图
        ctx.drawImage(img, 0, 0, width, height); /*绘图*/
        var dataURL = canvas.toDataURL("image/png", 0.9);//降低图片的清晰度

        return dataURL;
    }
</script>
</html>